package com.xyq.judge.config;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.netty.NettyDockerCmdExecFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DockerSandBoxPoolConfig {
    // docker连接的地址, 默认值 localhost2375
    @Value("${sandbox.docker.host:tcp://localhost:2375}")
    private String dockerHost;
    // 执行代码执行时间 默认: 6秒
    @Value("${sandbox.limit.time}")
    private Long timeLimit;

    // 内存限制
    @Value("${sandbox.limit.memory:100000000}")
    private Long memoryLimit;
    // 交换内存限制
    @Value("${sandbox.limit.memory-swap:100000000}")
    private Long memorySwapLimit;

    // cpu限制 默认 1
    @Value("${sandbox.limit.cpu:1}")
    private Long cpuLimit;

    // 容器镜像设置
    @Value("${sandbox.docker.image:openjdk:8-jdk-alpine}")
    private String sandboxImage;

    // 挂载地址设置
    @Value("${sandbox.docker.volume:/usr/share/java}")
    private String volumeDir;

    // 容器池里 容器的名字前缀 : 容器名=前缀+编号
    @Value("${sandbox.docker.name-prefix:oj-sandbox-jdk}")
    private String containerNamePrefix;

    // 容器池 默认容器数量
    @Value("${sandbox.docker.pool.size:4}")
    private int poolSize;


    // docker的连接
    @Bean
    public DockerClient createDockerClient() {
        // 创建docker
        DefaultDockerClientConfig clientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost(dockerHost)
                .build();
        // docker的  连接
        return DockerClientBuilder
                .getInstance(clientConfig)
                .withDockerCmdExecFactory(new NettyDockerCmdExecFactory())
                .build();
    }

    // 创建一个 docker容器池
    @Bean
    public DockerSandBoxPool createDockerSandBoxPool(DockerClient dockerClient) {
        // 创建容器池
        DockerSandBoxPool dockerSandBoxPool = new DockerSandBoxPool(dockerClient, sandboxImage, volumeDir, memoryLimit
                , memorySwapLimit, cpuLimit, poolSize, containerNamePrefix);
        // 初始化容器池
        dockerSandBoxPool.initDockerPool(poolSize);
        return dockerSandBoxPool;
    }

}
